<template lang="pug">
  .tobanScheduleWrapper
    .header
      h2 排课设置
      alert(type="warning" size="small" showIcon) {{warnText}}
    el-row(:gutter="12")
      el-col(:span="16")
        form-box(
          ref="form"
          :fields="items"
          :baseData="{ classesId, weekDay }"
          isFilter
          :showBtns="false"
        )
      el-col.tr(:span="8")
        .btnGroup
          el-button.gradientVertical(type="primary" size="large" round @click="exportExcel") 导出
          el-button.gradientVertical(v-if="canSchedule" size="large" round @click="tplObj.visible = true") 模版库
          el-button.mr30.btn-primary-box(size="large" round v-if="canSchedule" @click="saveTpl" plain) 保存为模板
          <!--el-button(type="success" size="large" round v-if="!isChecking" @click="checkSubmitHandle" :loading="checkSubmitting" plain) 发布-->
    el-tabs.dateTtab(v-model="weekDayValue" stretch)
      el-tab-pane(v-for="day in weekDays" :key="day" :name="day" :label="day")
    div(v-loading="loading")
      empty(v-if="nurseryScheduleRecordList.length < 1 && !canSchedule" title="暂无排课")
      toban-item(
        ref="tobanItem"
        v-for="(item, index) in nurseryScheduleRecordList"
        :key="item.id"
        :list="nurseryScheduleRecordList"
        :value="item"
        :canSchedule="canSchedule"
        :indexInList="index"
        @delHandle="delSchedule"
        @selectCourse="selectCourse"
        @saveSchedule="saveSchedule"
      )
      toban-item(
        v-if="addVisible"
        ref="tobanItemAdd"
        :isAdd="true"
        :list="nurseryScheduleRecordList"
        @selectCourse="selectCourse"
        @saveSchedule="saveSchedule"
      )
      p.addTxt.tc(v-if="canSchedule")
        a(javascript="javascript:void(0)" @click="() => addToggle(true)")
          i.iconfont.icon-020tianjia.mr5
          | 添加
      p.tr.mt20
        el-button.btn-primary-box(size="large" v-if="canSchedule" @click="autoSchedule" :loading="autoSubmitting" round plain) 自动排课
        el-button.gradientVertical(size="large" v-if="canSchedule" @click="submitHandle" :loading="submitting" round) 保存
    //- 课程选择
    course-selector(
      v-model="courseSelectObj.visible"
      :initCourse.sync="courseSelectObj.course"
      packageType="0"
      @sureHandle="saveSchedule"
    )
    nursery-tpls(
      v-model="tplObj.visible"
      @sureHandle="tplSureHandle"
    )
</template>
<script>
import dayjs from 'dayjs'
import Empty from '@/components/Basic/Empty'
import Alert from '@/components/Basic/Alert'
import { getDateFromWeek } from '@/utils/date'
import { sortByProperty } from '@/utils/util'
import { getNurseryClasses, getNurserySchule, getNurseryCheck, nurserySchuleSubmit, saveTemps, autoSchedule, checkSchedule, nurseryExportExcel } from '../api'
import TobanItem from '../components/tobanItem'
import CourseSelector from '../components/courseSelector'
import nurseryTpls from '../components/nurseryTpls'
import { mapGetters } from 'vuex'

const dateFormatStr = 'YYYY/MM/DD'

const warnStrs = [
  '请逐项添加详细的托班一日生活流程!',
  '本周课表已审核通过，不支持修改!',
  '本周课表正在审核中，暂时不能修改哦~',
  '当前日期已过，不支持排课！'
]

const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

const initDay = new Date().getDay()

export default {
  components: {
    Empty,
    Alert,
    TobanItem,
    CourseSelector,
    nurseryTpls
  },
  data () {
    return {
      loading: false,
      submitting: false,
      addVisible: false, // 是否显示新增项
      autoSubmitting: false, // 自动排课按钮submitting
      checkSubmitting: false, // 提交审核submitting
      weekDays, // 周列表
      weekDayValue: weekDays[initDay === 0 ? 6 : initDay - 1], // 周几
      nurseryScheduleId: '', // 当前日期的排课id
      nurseryScheduleRecordList: [], // 当前日期的排课列表
      checkInfo: null, // 审核详情
      courseSelectObj: {
        visible: false,
        course: null
      }, // 选择课程
      classes: [], // 班级列表
      classesId: '', // 排课班级
      weekDay: new Date(), // 排课日期
      tplObj: {
        visible: false
      }
    }
  },
  computed: {
    ...mapGetters(['curArea']),
    weekDuration () {
      return getDateFromWeek(this.weekDay)
    },
    curDateStr () {
      const { weekDay } = this
      return dayjs(weekDay).format(dateFormatStr)
    },
    // 当前是否支持排课
    canSchedule () {
      const { weekDay, checkInfo, isChecking } = this
      return checkInfo?.status !== 1 && !isChecking && weekDay.getTime() >= new Date(dayjs().format(dateFormatStr)).getTime()
    },
    // 排课提示语
    warnText () {
      const { weekDay, checkInfo, isChecking } = this
      if (checkInfo?.status === 1) {
        return warnStrs[1]
      }
      if (isChecking) {
        return warnStrs[2]
      }
      if (weekDay.getTime() < new Date().getTime() - 24 * 3600 * 1000) {
        return warnStrs[3]
      }
      return warnStrs[0]
    },
    isChecking () {
      const { checkInfo } = this
      return checkInfo && checkInfo.status !== 2
    },
    items () {
      const { classesId, weekDay } = this
      return [
        {
          key: 'classesId',
          type: 'select',
          initialValue: classesId,
          fieldProps: {
            placeholder: '班级选择',
            options: this.classes,
            props: { value: 'classesId', label: 'classesName' }
          },
          events: {
            change: val => this.searchFormChange(val, 'classesId')
          }
        },
        {
          key: 'weekDay',
          type: 'week',
          initialValue: weekDay,
          fieldProps: {
            pickerOptions: { firstDayOfWeek: 1 },
            format: 'yyyy 第 WW 周',
            placeholder: '时间选择'
          },
          events: {
            change: val => this.searchFormChange(val, 'weekDay')
          }
        }
      ]
    }
  },
  watch: {
    // 获取详情监听
    weekDay () {
      this.getInfo()
    },
    classesId () {
      this.getInfo()
      this.getCheck()
    },
    // 周几变化了，日期也要变化
    weekDayValue (val) {
      const { weekDuration } = this
      this.weekDay = new Date(weekDuration.dateArr[weekDays.indexOf(val)])
    },
    // 周变化之后重新获取审核信息
    'weekDuration.startDateString': {
      handler (val) {
        this.getCheck()
      }
    }
  },
  created () {
    this.getClasses()
  },
  methods: {
    // 获取排课详情
    getInfo () {
      const { classesId, curDateStr } = this
      this.loading = true
      getNurserySchule({ classesId, courseDateStr: curDateStr }).then(res => {
        this.addToggle(false)
        this.nurseryScheduleId = res?.nurseryScheduleId
        this.nurseryScheduleRecordList = res?.nurseryScheduleRecordList || []
      }).finally(() => {
        this.loading = false
      })
    },
    // 搜索栏form表单
    searchFormChange (val, key) {
      this[key] = val
      if (key === 'weekDay') {
        this.weekDayValue = weekDays[val.getDay() - 1]
      }
    },
    // 获取托班班级列表
    async getClasses () {
      const { classes } = this
      if (classes.length < 1) {
        this.classes = await (getNurseryClasses() || [])
      }
      this.classesId = this.classes[0]?.classesId || ''
    },
    // 获取审批信息
    getCheck () {
      const { classesId, weekDuration } = this
      const { dateArr } = weekDuration
      getNurseryCheck({
        classesId,
        beginDate: dateArr[0],
        endDate: dateArr[dateArr.length - 1]
      }).then(res => {
        this.checkInfo = res
      })
    },
    // 添加课程
    addToggle (flag = false) {
      this.addVisible = flag
    },
    // 删除排课
    delSchedule (id) {
      const { nurseryScheduleRecordList } = this
      this.nurseryScheduleRecordList = nurseryScheduleRecordList.filter(x => x.id !== id)
    },
    // 选择课程
    selectCourse (item) {
      console.log(item)
      this.courseSelectObj = {
        visible: true,
        course: item
      }
    },
    // 排课，flag-新增
    saveSchedule (item, flag) {
      this.addToggle(false)
      const { curDateStr } = this
      let list = this.nurseryScheduleRecordList
      console.log(item, flag)
      if (!flag) {
        list = list.map(x => {
          if (x.id === item.id) {
            x = item
          }
          return x
        })
        const tobanItemRefs = this.$refs.tobanItem
        tobanItemRefs.map(ref => {
          ref.editHandle(false, false)
        })
      } else {
        const tobanItemAddRef = this.$refs.tobanItemAdd
        tobanItemAddRef.course = {
          remark: '',
          timeRange: [new Date('1990-01-01 8:00:00'), new Date('1990-01-01 18:00:00')]
        }
        list.push(item)
      }
      list.map(x => {
        x.beginDate = new Date(curDateStr + ' ' + x.begin).getTime()
        x.endDate = new Date(curDateStr + ' ' + x.end).getTime()
        return x
      })
      this.nurseryScheduleRecordList = list.sort(sortByProperty('begin', 'time'))
    },
    // 保存模板
    saveTpl () {
      const { curArea, curDateStr, nurseryScheduleRecordList } = this
      this.$prompt('请输入模版名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        saveTemps({
          areaId: curArea.areaId
        }, {
          name: value,
          lessonDate: curDateStr,
          scheduleJson: JSON.stringify(nurseryScheduleRecordList.map(({ activityContent, begin, end, category, resObj }) => {
            return {
              activityContent,
              begin,
              end,
              category: Number(category),
              resObj
            }
          }))
        }).then(() => {
          this.$message.success('保存成功')
        })
      })
    },
    // 载入模板
    tplSureHandle (tpl) {
      console.log(tpl)
      this.nurseryScheduleRecordList = [...tpl]
    },
    // 提交审核
    checkSubmitHandle () {
      const { weekDuration, classesId, curArea } = this
      this.$confirm('确认提交本次排课计划吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.autoSubmitting = true
        checkSchedule({ areaId: curArea.areaId }, {
          checkId: '',
          isSure: 1,
          classesId,
          beginDate: weekDuration.dateArr[0],
          endDate: weekDuration.dateArr[weekDuration.dateArr.length - 1]
        }).then(() => {
          this.$message.success('提交成功')
          this.getInfo()
          this.getCheck()
        }).finally(() => {
          this.autoSubmitting = false
        })
      })
    },
    // 自动排课
    autoSchedule () {
      const { curDateStr, classesId } = this
      this.$confirm(`此操作将自动排${curDateStr}的课, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.autoSubmitting = true
        autoSchedule({
          classesId,
          lessonDate: curDateStr
        }).then(() => {
          this.$message.success('提交成功')
          this.getInfo()
        }).finally(() => {
          this.autoSubmitting = false
        })
      })
    },
    // 保存排课
    submitHandle () {
      const { nurseryScheduleId, classesId, curDateStr, nurseryScheduleRecordList } = this
      console.log(nurseryScheduleRecordList)
      const params = {
        scheduleJson: JSON.stringify(nurseryScheduleRecordList.map(x => {
          const { isAdd, id, activityContent, begin, end, category, resObj, remark } = x
          const obj = {
            activityContent,
            begin,
            end,
            category: Number(category),
            resObj,
            remark
          }
          if (isAdd) {
            return obj
          } else {
            return {
              id,
              beginDate: new Date(curDateStr + ' ' + begin).getTime(),
              endDate: new Date(curDateStr + ' ' + end).getTime(),
              ...obj
            }
          }
        }))
      }
      if (nurseryScheduleId) {
        params.nurseryScheduleId = nurseryScheduleId
      } else {
        params.classesId = classesId
        params.lessonDate = curDateStr
      }
      this.submitting = true
      nurserySchuleSubmit(params, nurseryScheduleId ? 'update' : 'add').then(res => {
        if (res) {
          this.getInfo()
        }
      }).finally(() => {
        this.submitting = false
      })
    },

    exportExcel () {
      const { classesId, weekDuration } = this
      const { dateArr } = weekDuration
      const params = {
        classesId,
        courseDateStr: dateArr[0]
      }
      console.log(params)
      nurseryExportExcel(params).then(res => {
        top.location.href = res
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.tobanScheduleWrapper {
  >.header {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    >h2 {
      margin-right: 12px;

      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: bold;
      font-size: 18px;
      color: #000;
      text-align: left;
      font-style: normal;
      text-transform: none;
    }
  }
}

.btnGroup {
  position: absolute;
  right: 0;
  top: 0
}

.dateTtab {
  ::v-deep {
    >.el-tabs__header {
      margin-bottom: 0
    }

    .el-tabs__item {
      padding: 0;
      height: 66px;
      line-height: 66px;
      background: #FAFAFA;
      font-size: 17px;
      font-family: PingFang SC;
      ;
      color: #6E645A;
      position: relative;

      &::before {
        content: '';
        display: block;
        height: 1px;
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        background: #E8E8E8;
        z-index: 5;
      }

      &.is-active,
      &:hover {
        color: #333333;

        &::before {
          height: 5px;
          background: linear-gradient(90deg, $--app-linear-gradient-stop1 0%, $--app-linear-gradient-stop2 100%);
        }
      }
    }

    .el-tabs__nav-wrap::after,
    .el-tabs__active-bar {
      display: none;
    }
  }
}

.el-tabs__nav {}

.weekWrapper {
  position: relative;

  .weekStr {
    position: relative;
    z-index: 0;
  }

  .weekInput {
    position: absolute;
    z-index: 10;
    width: 100%;
    height: 100%;
    opacity: 0;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0
  }
}

.el-divider--horizontal {
  margin-top: 36px
}

.addTxt {
  font-size: 15px;
  font-family: PingFang SC;
  color: #999999;
  padding: 32px 0;
  border-bottom: 1px dashed #E8E8E8;

  i {
    font-size: 20px;
    vertical-align: middle;
  }
}
</style>
